<template>
  <el-form
    ref="userForm"
    :model="userInfo"
    :rules="rules"
    label-width="120px"
    style="margin-left: 120px; margin-top: 30px"
  >
    <el-form-item label="姓名:" prop="username">
      <el-input v-model="userInfo.username" style="width:300px" />
    </el-form-item>
    <el-form-item label="密码:" prop="password">
      <el-input v-model="userInfo.password" type="password" style="width:300px" />
    </el-form-item>

    <el-form-item>
      <el-button type="primary" @click="submit">更新</el-button>
    </el-form-item>
  </el-form>
</template>

<script>
// 获取员工信息
import { getUserDetailById } from '@/api/user'
// 保存员工信息
import { saveUserDetailById } from '@/api/employees'
export default {
  data() {
    return {
      userInfo: {
        username: '',
        password: ''
      },
      rules: {
        username: [{ required: true, message: '用户名不能为空', trigger: 'blur' }],
        password: [{ required: true, message: '密码不能为空', trigger: 'blur' }]
      }
    }
  },
  created() {
    // 获取员工信息
    this.getUser()
  },
  methods: {
    // 获取员工信息
    async getUser() {
      try {
        // 通过查询字符串获得id
      // console.log(this.$route.query.id)
        const res = await getUserDetailById(this.$route.query.id)
        // console.log(res.data, 111)
        // 解构
        // const { username, password,id } = res.data
        // this.userInfo.username = username
        // this.userInfo.password = password
        // 直接赋值
        // this.userInfo = { username, password,id }
        this.userInfo = res.data
      } catch (err) {
        console.log('获取数据失败')
        this.$message.error('获取数据失败')
      }
    },
    // 保存员工信息
    async updated() {
      try {
        await saveUserDetailById(this.userInfo)
        this.$message.success('保存成功')
        // 页面回退
        // this.$router.back()
      } catch (err) {
        console.log('保存失败', err)
        this.$message.error('保存失败')
      }
    },
    // 点击更新按钮
    submit() {
      this.$refs.userForm.validate(valide => {
        if (!valide) return
        this.updated()
      })
    }
  }
}
</script>

